package cn.t222.service;

import cn.t222.mapper.SysResourcesMapper;
import cn.t222.pojo.SysResources;
import cn.t222.pojo.SysRole;
import cn.t222.pojo.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Service("rbacService")
@Slf4j
public class RbacServiceImpl implements RbacService {
    @Autowired
    private ResourceService resourceService;

    /**
     * 判断用户是否有权访问其请求的路径（url,api,接口）
     * 1、获取用户拥有的角色集合
     * 2、获取用户角色用户的权限集合
     * 3、比较用户访问的url是否在权限的集合中
     * @param request
     * @param authentication
     * @return
     */
    @Override
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        Object principal = authentication.getPrincipal();
        boolean hasPermission = false;
        if (principal != null && principal instanceof UserDetails) {
            String userName = ((UserDetails) principal).getUsername();
            List<SysResources> resourcesList = resourceService.getAllByUsername(userName);
            //用户的权限集合
            List<String> urls = new ArrayList<>();
            resourcesList.forEach(sysResources1 -> {
                if(sysResources1.getUrl() != null && !sysResources1.getUrl().equals("")) {
                    urls.add(sysResources1.getUrl());
                }
            });
            String url = request.getRequestURI();
            log.info("用户名：{}", userName);
            log.info("用户名：{},权限:{}", userName, urls);
            for(String s: urls) {
                if(s!=null && s.equals(url)) {
                    hasPermission = true;
                    break;
                }
            }
            log.info("用户名：{},请求url：{},结果：{}",userName, url, hasPermission);
        }
        return hasPermission;
    }
}
